<template>
  <div class="bg-box">
    <div class="left">
      <!-- <img src="../../assets/images/het-logo.svg" class="logo-img" alt="" /> -->
      <p style="color: #fff">系统漏洞与安全威胁检索系统</p>
    </div>
    <div class="right">
      <div class="login-box">
        <h1 class="welcomeToLogin">欢迎登录</h1>
        <el-form class="form-box" ref="logForm" :model="form" :rules="formRules">
          <el-form-item prop="username">
            <el-input v-model="form.username" type="text" class="login-input-size login-input-background" autocomplete="no" placeholder="请输入用户名">
              <template #prefix> <img src="../../assets/images/user.svg" alt="" class="input-img" /><span class="input-division-line"></span> </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="form.password" class="login-input-size login-input-background" autocomplete="new-password" show-password placeholder="请输入密码">
              <template #prefix> <img src="../../assets/images/pwd.svg" alt="" class="input-img" /><span class="input-division-line"></span> </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="verifycode">
            <el-input v-model="form.verifycode" class="login-input-size code-size login-input-background" placeholder="验证码">
              <template #prefix> <img src="../../assets/images/code.svg" alt="" class="input-img" /><span class="input-division-line"></span> </template>
            </el-input>
            <p id="captcha" @click="getVerifyCode" style="margin-left: 30px; cursor: pointer">
              {{ verifycode }}
            </p>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" class="login-input-size login-color" @click="loginFn">立即登录 </el-button>
          </el-form-item>
          <!-- <el-form-item label="卫士客户端下载">
            <el-link
              class="font-size ml-4 link-background"
              :href="installFn(1)"
              type="primary"
              :underline="false"
            >
              <img
                src="../../assets/images/windows.svg"
                alt=""
                class="mr-1.5"
              />
              Windows
            </el-link>
            <el-link
              class="font-size ml-5 link-background"
              type="primary"
              :href="installFn(0)"
              :underline="false"
            >
              <img src="../../assets/images/linux.svg" alt="" class="mr-1.5" />
              Linux
            </el-link>
          </el-form-item> -->
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getSecretKey, verifyImage, loginSbumit, getHomeInfo } from '~/utils/axios/login.js'
import { req_getProductionInfo } from '~/utils/axios/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { enCrypto } from '~/common/crypto.js'
import { useRouter } from 'vue-router'
import { useUserStore } from '~/utils/pinia/user.js'
import { URI, mAxios } from '~/utils/axios/axios.js'
const verifycode = ref('')
let $router = useRouter()
let loading = ref(false)
const userStore = useUserStore()
const logForm = ref()
const verifyImageValue = ref('')
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 24, message: '长度在 3 到 25 个字符', trigger: 'blur' }
  ],
  verifycode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '长度为 4 个字符', trigger: 'blur' }
  ]
}
const form = reactive({
  username: 'admin',
  password: 'admin123',
  verifycode: ''
})
const loginFn = async () => {
  await logForm.value.validate()
  if (form.verifycode != verifycode.value.toLowerCase()) {
    ElMessage.error('验证码验证失败，请重试')
    form.verifycode = ''
    getVerifyCode()
    return
  }
  loading.value = true

  // let key = await getSecretKey();
  // const info = {
  //   username: btoa(enCrypto(form.username, key.data)),
  //   password: btoa(enCrypto(form.password, key.data)),
  //   verifycode: btoa(form.verifycode),
  // };
  // loginSbumit(info)
  //   .then((loginReq) => {
  //     if (loginReq.data.success) {
  //       // 密码过期或者未注册
  //       sessionStorage.setItem(
  //         "register",
  //         JSON.stringify(loginReq.data.loginedUser)
  //       );
  //       // if (!loginReq.data.loginedUser.isRegister) {
  //       //   $router.push({
  //       //     path: "/password",
  //       //     query: {
  //       //       name: loginReq.data.loginedUser.name,
  //       //       userId: loginReq.data.loginedUser.userId,
  //       //     },
  //       //   });
  //       // } else
  //       if (loginReq.data.loginedUser.name == "root") {
  //         $router.push("/DOMAIN");
  //       } else if (loginReq.data.loginedUser._roles[0].name === "安全审计员") {
  //         $router.push("/auditlog");
  //       } else if (loginReq.data.loginedUser._roles[0].name === "系统管理员") {
  //         $router.push("/systemsetting");
  //       } else {
  //         $router.push("/home");
  //       }
  //       userStore.name = loginReq.data.loginedUser.name;
  //       userStore.loginState = true;
  //       loading.value = false;
  //     } else {
  //       ElMessage.error(loginReq.data.message);
  //       form.verifycode = "";
  //       getVerifyImage(); // 重新获取验证码
  //       loading.value = false;
  //     }
  //   })
  //   .catch((error) => {
  //     // 登录失败加载也消失
  //     loading.value = false;
  //   });
  const info = {
    username: form.username,
    password: form.password
  }
  mAxios
    .post('auth/login', info)
    .then(res => {
      loading.value = false
      if (res.data.succeed) {
        ElMessage.success('登录成功')
        for (let k in res.data.data) {
          sessionStorage.setItem(k, res.data.data[k])
        }
        $router.push({ path: '/home' })
      } else {
        ElMessage.error(res.data.message)
        // getVerifyCode();
      }
    })
    .catch(error => {
      loading.value = false
    })
}
const getVerifyCode = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let captcha = ''
  for (let i = 0; i < 4; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length)
    captcha += characters.charAt(randomIndex)
  }
  verifycode.value = captcha
}
// 客户端下载函数
const installFn = type => {
  return window.location.protocol + '//' + window.location.host + URI + 'versionManager/package/install?os=' + type
}
const productName = ref()
const getProductionInfo = async () => {
  const { data: res } = await req_getProductionInfo()
  productName.value = res.productName
  if (!sessionStorage.getItem('productInfo')) {
    sessionStorage.setItem('productInfo', JSON.stringify(res))
  }
}
onMounted(() => {
  // getVerifyImage();
  // getHomeInfo().then(res => {
  //     console.log(res)
  // })
  // getProductionInfo();
  getVerifyCode()
})
</script>

<style lang="scss" scoped>
.bg-box {
  display: flex;
  justify-content: center;
  background: url(../../assets/images/bg0.png) no-repeat center center / cover fixed;
}

.left,
.right {
  width: 50%;
}

.left {
  position: absolute;
  top: 54px;
  left: 62px;

  .logo-img {
    display: inline-block;
    height: 44px;
  }

  p {
    display: inline-block;
    font-size: 22px;
    font-weight: 400;
    margin-left: 20px;
  }
}

.login-box {
  position: fixed;
  right: 16.67%;
  top: 22.96%;
  width: 416px;
  height: 480px;
  border-radius: 12px;
  background: #ffffff;
  box-shadow: 0 2px 15px 0 rgba(120, 78, 78, 0.3);
}

.form-box {
  width: 330px;
  margin: 0 auto;
}

.welcomeToLogin {
  font-weight: bold;
  font-size: 27px;
  color: #02112b;
  font-style: normal;
  text-transform: none;
  margin: 50px 0;
  text-align: center;
}

.login-input-size,
.code-size {
  width: 100%;
  height: 45px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.45);

  :deep(.el-input__wrapper) {
    background-color: rgba(0, 0, 0, 0.03);
    border-radius: 8px;
    box-shadow: none;
    .el-input__inner {
      color: #000;
    }
  }
}
.code-size {
  width: 200px;
}

.code-img {
  width: 116px;
  height: 43px;
  margin-left: 12px;
  line-height: 20px;
  :deep(.el-image__inner) {
    border-radius: 8px;
  }
}
.link-background {
  color: #973397;
}
:deep(.form-box .el-input__prefix) {
  // color: #6c216d;
  font-size: 24px;
}

.input-division-line {
  display: inline-block;
  width: 1px;
  height: 26px;
  background-color: rgba(0, 0, 0, 0.45);
  margin-left: 12px;
}

.input-img {
  width: 18px;
  height: 18px;
}

.login-color {
  color: #fff;
  background-color: #973397 !important;
  border-radius: 8px !important;
}
</style>
